/* Copyright (c) [2025] [zhi1208@126.com]
 * SPDX-License-Identifier: MIT
 */

/*********************
 *      INCLUDES
 *********************/
#include "stm32f4xx_hal.h"

/*********************
 *      DEFINES
 *********************/

/**********************
 *      TYPEDEFS
 **********************/

/**********************
 *  STATIC PROTOTYPES
 **********************/

/**********************
 *  STATIC VARIABLES
 **********************/

/**********************
 *      MACROS
 **********************/

/**********************
 *   GLOBAL FUNCTIONS
 **********************/
void bsp_delay_us(uint32_t us)
{
    if (us > (UINT32_MAX / (SystemCoreClock / 1000000)))
        return;

    uint32_t target_ticks = us * (SystemCoreClock / 1000000);
    uint32_t systick_reload = SysTick->LOAD;

    uint32_t elapsed_ticks = 0;
    uint32_t current_tick = 0;
    uint32_t previous_tick = SysTick->VAL;

    while (elapsed_ticks < target_ticks)
    {
        current_tick = SysTick->VAL;
        if (current_tick != previous_tick)
        {
            if (current_tick < previous_tick)
                elapsed_ticks += previous_tick - current_tick;

            else
                elapsed_ticks += systick_reload - current_tick + previous_tick;
        }
    }
    previous_tick = current_tick;
}

/**********************
 *   STATIC FUNCTIONS
 **********************/